package net.techwatch.gwt.json.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Gwt_json implements EntryPoint, ClickHandler, KeyUpHandler {

	private TextBox firstName = new TextBox();
	private TextBox lastName = new TextBox();

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		final Button displayButton = new Button("Submit");

		firstName.setSize("150px", "25px");
		lastName.setSize("150px", "25px");

		displayButton.addClickHandler(this);
		displayButton.addKeyUpHandler(this);

		RootPanel.get("button").add(displayButton);
		RootPanel.get("firstName").add(firstName);
		RootPanel.get("lastName").add(lastName);
	}

	@Override
	public void onClick(ClickEvent event) {
		displayMessage();

	}

	@Override
	public void onKeyUp(KeyUpEvent event) {
		if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
			displayMessage();
		}

	}

	private void displayMessage() {
		RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, GWT
				.getHostPageBaseURL()
				+ "json_servlet");
		builder.setHeader("Content-Type", "application/x-www-form-urlencoded");
		
		try {
			StringBuilder paramsBuilder = new StringBuilder();
			paramsBuilder.append("firstName=");
			paramsBuilder.append(URL.encodeComponent(firstName.getText()));
			paramsBuilder.append("&lastName=");
			paramsBuilder.append(URL.encodeComponent(lastName.getText()));
			
			builder.sendRequest(paramsBuilder.toString(), new RequestCallback() {

				@Override
				public void onResponseReceived(Request request,
						Response response) {
					String content = response.getText();
					Person person = (Person) Person.evaluateJSon(content);
					String message = "<b>Your name is: " + person.getFirstName() + " " + person.getLastName() + "</b>";
					RootPanel.get("message").add(new HTML(message));
				}

				@Override
				public void onError(Request request, Throwable exception) {
					GWT.log("Error on request", exception);
				}
			});
		} catch (RequestException e) {
			GWT.log("Error while requesting ressource", e);
		}
	}	
}
